package com.controller;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import javax.xml.ws.RespectBinding;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.entity.Role;
import com.entity.User;
import com.entity.page.Page;
import com.exception.NoLoginException;
import com.service.RoleService;
import com.service.UserService;

//控制层
@Controller
@RequestMapping("user")
public class UserController
// 局部异常处理1
// implements HandlerExceptionResolver
{

	//3 格式化转换
	@InitBinder
	public void initBinder(WebDataBinder dataBinder){
		//注册自定义格式转换
		dataBinder.registerCustomEditor(Date.class, 
					new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"),true)
				);
	}
	
	@Autowired
	UserService userService;

	@Autowired
	RoleService roleService;

	@RequestMapping("/login")
	public String login(String userCode, String userPassword, Model model, HttpSession session) {
		User user = userService.login(userCode, userPassword);
		if (user == null) {
			// 失败
			model.addAttribute("error", "用户名密码错误！");
			return "login";
		}
		// 成功
		session.setAttribute("userSession", user);

		return "redirect:/main";// 重定向请求url 不是逻辑视图
	}

	@GetMapping("/list")
	public String list(@RequestParam(defaultValue = "1", required = false) Integer pageIndex, String queryname,
			Integer queryUserRole, Model model, HttpSession session) {

		Page<User> pageInfo = userService.selectByUserPage(pageIndex, queryname, queryUserRole);
		model.addAttribute("pageInfo", pageInfo);

		model.addAttribute("queryUserName", queryname);
		model.addAttribute("queryUserRole", queryUserRole);

		model.addAttribute("roleList", roleService.selectRoleAll());
		return "userlist";
	}

	@ResponseBody
	@RequestMapping("/getrolelist")
	public List<Role> getrolelist(){
		return roleService.selectRoleAll();
	}
	@RequestMapping("toadd")
	public String toAdd(Model model) {

		//model.addAttribute("roleList", roleService.selectRoleAll());
		return "useradd";
	}

	@RequestMapping("add")
	public String add(@Valid User user,BindingResult bindingResult, MultipartFile idPicFile // 证件照
			, Model model) {
		
		//验证
		if(bindingResult.hasErrors()){
			Map<String, String> errorsMap = new HashMap<>();
			for (FieldError fieldError : bindingResult.getFieldErrors()) {
				errorsMap.put(fieldError.getField(), fieldError.getDefaultMessage());
			}
			model.addAttribute("errors", errorsMap);
			return "useradd";
		}

		if (!idPicFile.isEmpty()) {
			// 保存
			try {
				// 防止文件重复
				String ext = idPicFile.getOriginalFilename()
						.substring(idPicFile.getOriginalFilename().lastIndexOf("."));
				String idPicPath = System.currentTimeMillis() + "_Personal" + ext;
				idPicFile.transferTo(new File("E:\\files\\" + idPicPath));
				// 成功
				user.setIdPicPath(idPicPath);
			} catch (Exception e) {
				e.printStackTrace();
			}
		} 

		boolean f = userService.addUser(user);
		if (f) {

			return "redirect:list";
		}

		model.addAttribute("error", "添加失败");
		model.addAttribute("roleList", roleService.selectRoleAll());
		return "useradd";
	}

	//rest风格
	@RequestMapping("view/{id}") //占位符{id}
	public String view(@PathVariable Long id,//注解
			Model model){
		User user = userService.selectUserById(id);
		model.addAttribute("user", user);
		return "userview";
	}
	
	@ResponseBody
	@RequestMapping(
			value="/ajaxview/{id}"
			//produces="application/json;charset=UTF-8" //指定返回数据类型的编码
	)
	public User ajaxView(@PathVariable Long id){
		User user = userService.selectUserById(id);
//		return JSON.toJSONString(user);
		return user;
	}
	
	//用户code是否存在
	@ResponseBody//返回不是逻辑视图 是数据
	@RequestMapping("ucexist")
	public String userCodeIsExit(String userCode){
		boolean f =  userService.ucexist(userCode);
		Map<String, Object> map  = new HashMap<>();
		map.put("userCode", f?"exist":"noexist");
		return JSON.toJSONString(map);
	}
	
	@ResponseBody
	@RequestMapping("/deluser/{id}")
	public Map<String, Object> deluser(@PathVariable Integer id){
		Map<String, Object> map  = new HashMap<>();
		
		boolean f = userService.deleteUserById(id);
		map.put("delResult", f + "");
		return map;
	}
	
	
	// 局部异常2
	// 使用注解
	// @ExceptionHandler
	// public String error(Exception e) {
	// e.printStackTrace();
	// ModelAndView andView = new ModelAndView("error");
	// return "error";
	// }

	@RequestMapping("/fm")
	public String fm(@ModelAttribute("user") User user) {
		return "spfm";
	}

	@RequestMapping("fmadd")
	public String fmAdd(@Valid User user, BindingResult bindingResult, Model model) {
		if (bindingResult.hasErrors()) {
			// 验证没通过
			return "spfm";
		}
		return "redirect:list";
	}
}
